import { Radio, Space, Button, message, Modal, Table } from 'antd';
import { CheckItemContent } from './component';
import { useRequest } from 'ahooks';
import { useEffect } from 'react';
import {
  GetLatestItemCode,
  GetPWorkItemComInfo,
  InsertWorkInfo,
  SaveWorkItemOperate,
  WorkItemDelete,
} from '../api/work';
import appState from '../sotre';
import { useSnapshot } from 'valtio';
import { useProxy } from 'valtio/utils';
import styles from './index.module.less';
import appWorkState from './store';
import EventDataView from './event-data';
import FileLinkView from './file-link';
import TopFooterView from './top-footer';
import { cloneDeep } from 'lodash';

const topBtnList = [
  { value: 'f1', label: '事务项' },
  { value: 'f2', label: '数据项' },
  { value: 'f3', label: '文件链接' },
  // { value: 'f4', label: '页眉页脚' },
];
const secondBtnList = ['删除', '事务', '标题', '选项', '填写', '描述']; //'升级', '降级',

const addTitle = () => {};
const addWorkTitle = () => {};

const ContentView = () => {
  const store = useSnapshot(appState);
  const workStore = useProxy(appWorkState);
  const { formVerId, factory } = store;
  const { currentTabId } = workStore;
  const getPWorkItemComInfo = useRequest(GetPWorkItemComInfo, { manual: true });
  const insertWorkInfo = useRequest(InsertWorkInfo, { manual: true });
  const saveWorkItemOperate = useRequest(SaveWorkItemOperate, { manual: true });
  const workItemDelete = useRequest(WorkItemDelete, { manual: true });
  // 获取最新ID
  const getLatestItemCode = useRequest(GetLatestItemCode, { manual: true });

  useEffect(() => {
    formVerId && getPWorkItemComInfo.run(formVerId || '');
    console.log('refresh', formVerId);
  }, [formVerId]);

  useEffect(() => {
    if (!workStore.currentItemKeyList) {
      return;
    }

    console.log(workStore.currentItemKeyList);
  }, [workStore.currentItemKeyList]);

  const clickBtn = async (title: string) => {
    console.log('title', title);
    const selTxt = await factory.getCurrentTxt();
    switch (title) {
      case '事务':
        if (!(selTxt?.length > 0)) {
          return message.error('请选择事务名称！');
        }
        await insertWorkInfo.runAsync({
          FORM_VER_ID: window.formVerId,
          WORK_NAME: selTxt,
          WORK_NO: '',
        });
        message.success('事务添加成功');
        getPWorkItemComInfo.refresh();
        break;
      case '标题':
        if (!(selTxt?.length > 0)) {
          return message.error('请选择标题名称！');
        }
        if (!workStore.currentWorkId) {
          return message.error('请选中事务项！');
        }
        // const workList = getPWorkItemComInfo.data || [];
        // const curWorkItem = workList.flatMap((v) => v.pchildWorkForm);
        // const lastItem = curWorkItem?.[curWorkItem.length - 1];
        // console.log('curWorkItem', workList, curWorkItem, lastItem);
        // const strList = lastItem?.ITEM_CODE?.split('_') || [];

        // 获取最新书签
        const resItemCode = await getLatestItemCode.runAsync(appState.formVerId);
        const strList = resItemCode?.split('_') || [];

        const itemCodeInt = parseInt(strList?.[1] || '0') + 1;
        const itemCodeIntStr = itemCodeInt?.toString()?.padStart(3, '0');
        const itemCode = `SO_${itemCodeIntStr}`;

        await factory.addBookmarkWithTitle(itemCode);
        await saveWorkItemOperate.runAsync({
          WORK_ID: workStore.currentWorkId,
          ITEM_CODE: itemCode,
          ITEM_SORT: itemCodeIntStr,
          ITEM_CNAME: `${selTxt}`,
          ITEM_BOOKMARK: '0,0',
          ITEM_ID: '',
        });

        message.success('标题添加成功');
        getPWorkItemComInfo.refresh();
        break;
      case '删除':
        Modal.confirm({
          title: '是否删除！',
          onOk: async () => {
            let type = '1';
            const workList = getPWorkItemComInfo.data?.find(
              (v) => v.WORK_ID === workStore.currentWorkId,
            ).pchildWorkForm;
            if (workStore.currentItemKeyList?.length === workList?.length) {
              type = '0';
            }
            if (!workStore.currentWorkId) {
              message.error('请选中事务项');
            }
            return await workItemDelete
              .runAsync({
                TYPE: type,
                WORK_ID: workStore.currentWorkId,
                ITEM_IDS: (workStore.currentItemKeyList as string[]) || [],
              })
              .then(() => {
                message.success('删除成功');
                const selItemIds = cloneDeep(workStore.currentItemKeyList);
                const combineList = getPWorkItemComInfo.data
                  ?.flatMap((v1) => {
                    return v1.pchildWorkForm;
                  })
                  .filter((v1) => selItemIds?.find((v2) => v1.ITEM_ID === v2))
                  .map((v) => v.ITEM_CODE);

                const handleList = combineList?.flatMap((v) => {
                  const splitStr = v.split('_');
                  const fd = splitStr?.[0] === 'SO' ? v : [`SO_${splitStr?.[1]}`, v];
                  return fd;
                });

                appState.factory.removeBookmark(handleList);
                workStore.currentItemKeyList = undefined;
              })
              .finally(() => {
                getPWorkItemComInfo.refresh();
              });
          },
        });
        break;
      case '选项':
      case '填写':
      case '描述':
        if (!(selTxt?.length > 0)) {
          return message.error('请选择选项名称！');
        }
        if (!workStore.currentWorkId) {
          return message.error('请选中事务项！');
        }
        if (!workStore.currentWorkId) {
          return message.error('请选中标题！');
        }

        const workListOp = getPWorkItemComInfo.data?.find((v) => v.WORK_ID === workStore.currentWorkId).pchildWorkForm;
        const selTitleOp = workListOp?.find((v) => v.ITEM_ID === workStore.currentItemTitleId);

        const strListOp = selTitleOp?.ITEM_CODE?.split('_') || [];
        const itemCodeIntOp = strListOp?.[1] || '001';
        const subfixTxt = title === '选项' ? 'CO' : title === '填写' ? 'PO' : 'EO';
        const itemCodeOp = `${subfixTxt}_${itemCodeIntOp}`;

        await factory.addBookmarkWithTitle(itemCodeOp);
        await saveWorkItemOperate.runAsync({
          WORK_ID: workStore.currentWorkId,
          ITEM_CODE: itemCodeOp,
          ITEM_SORT: '',
          ITEM_CNAME: `${selTxt}`,
          ITEM_BOOKMARK: '0,0',
          ITEM_ID: selTitleOp.ITEM_ID,
        });

        message.success('选项添加成功');
        getPWorkItemComInfo.refresh();
        break;

      default:
        break;
    }
  };

  return (
    <div className={styles.index}>
      <Space direction="vertical" size={4}>
        <Radio.Group
          size="middle"
          onChange={(v) => {
            workStore.currentTabId = v.target.value;
            workStore.currentItemTitleId = undefined;
          }}
          defaultValue="f1"
          value={currentTabId}
          optionType="button"
          options={topBtnList}
        />
        <Space size={4} style={{ padding: '5px 0' }} hidden={currentTabId !== 'f1'}>
          {secondBtnList.map((v) => {
            return (
              <Button size="small" key={v} onClick={() => clickBtn(v)}>
                {v}
              </Button>
            );
          })}
        </Space>
      </Space>
      {currentTabId === 'f1' && (
        <div className={styles.list}>
          <CheckItemContent itemList={getPWorkItemComInfo.data} />
        </div>
      )}
      {currentTabId === 'f2' && (
        <div className={styles.list}>
          <EventDataView />
        </div>
      )}
      {currentTabId === 'f3' && (
        <div className={styles.list}>
          <FileLinkView />
        </div>
      )}
      {currentTabId === 'f4' && (
        <div className={styles.list}>
          <TopFooterView />
        </div>
      )}
    </div>
  );
};

export default ContentView;
